package com.yjht.online.generate.impl.org;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.yjht.online.generate.GenerateSqlMould;
import com.yjht.online.util.OnLineFileUtil;

import java.io.File;
import java.util.List;

public abstract class GenerateSqlMouldBase<T> implements GenerateSqlMould<T> {
    @Override
    public void proccesor(List<T> list) {

        StringBuilder stringBuilder = new StringBuilder();
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());
        String sqlTemplate = getSqlTemplate();
        Template template = engine.getTemplate(sqlTemplate);

        for (T item : list) {
            String sql = template.render(BeanUtil.beanToMap(item));
            stringBuilder.append(sql);
            stringBuilder.append("\n\r");
        }
        String fileName = getOutPutPath()+ StrUtil.SLASH +getFileName();
        File file =  OnLineFileUtil.getOutPutFile(fileName);
        //FileUtil.mkParentDirs(path);
        FileUtil.del(file);
        FileUtil.touch(file);
        FileUtil.writeBytes(stringBuilder.toString().getBytes(), file);
    }

    protected abstract String getSqlTemplate();

    protected abstract String getOutPutPath();

    protected abstract String getFileName();
}
